package com.simon.hse.activity.contractor;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.google.gson.Gson;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonAdapter;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.Constants;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.AddExaminRecordInput;
import com.simon.hse.http.entity.CommonOutput;
import com.simon.hse.http.entity.ContractorCompanyOutput;
import com.simon.hse.http.entity.ContractorPersonOutput;
import com.simon.hse.http.entity.DropDownInput;
import com.simon.hse.http.entity.DropDownOutput;
import com.simon.hse.http.entity.ExaminDetailOutput;
import com.simon.hse.http.entity.ExaminRecordListOutput;
import com.simon.hse.http.entity.TrainCourseOutput;
import com.simon.hse.http.entity.UploadFileOutput;
import com.simon.hse.utils.DateTimeUtils;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.SelectPicUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 新增考试记录
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_add_examin_record)
public class AddExaminRecordActivity extends BaseActivity {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.ll_examin_name)
    LinearLayout mLl_examin_name;

    @ViewInject(R.id.tv_examin_name)
    TextView mTv_examin_name;

    @ViewInject(R.id.ll_examin_person)
    LinearLayout mLl_examin_person;

    @ViewInject(R.id.tv_examin_person)
    TextView mTv_examin_person;

    @ViewInject(R.id.tv_examin_date)
    TextView mTv_examin_date;

    @ViewInject(R.id.ll_examin_degree)
    LinearLayout mLl_examin_degree;

    @ViewInject(R.id.tv_examin_degree)
    TextView mTv_examin_degree;

    @ViewInject(R.id.et_examin_score)
    EditText mEt_examin_score;

    @ViewInject(R.id.ll_examin_constractor)
    LinearLayout mLl_examin_constractor;

    @ViewInject(R.id.tv_examin_constractor)
    TextView mTv_examin_constractor;

    @ViewInject(R.id.ll_examin_pass)
    LinearLayout mLl_examin_pass;

    @ViewInject(R.id.tv_examin_pass)
    TextView mTv_examin_pass;

    @ViewInject(R.id.et_examin_mark)
    EditText mEt_examin_mark;

    @ViewInject(R.id.rv_pic)
    RecyclerView mRv_pic;


    private ExaminRecordListOutput.DataBean.PageDataBean pageDataBean;
    private String id, cbsListId;
    private String cbsCourseId, examinerId, degreeOfDifficulty;
    private Boolean isPass;
    private List<DropDownOutput.DataBean.DataDicListBean.ValueBean> mListDegree = new ArrayList<>();// 难易程度

    private CommonAdapter mCommonAdapter;
    private List<String> mPicList = new ArrayList<>();
    private List<String> mPicIdList = new ArrayList<>();
    private String trainCourseId, trainPersonId, participantName, participantId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initPicRecyclerView();
        initData();
    }

    @Event(value = {R.id.iv_common_left
            , R.id.ll_examin_name, R.id.ll_examin_person, R.id.ll_examin_date, R.id.ll_examin_degree, R.id.ll_examin_constractor, R.id.ll_examin_pass
            , R.id.tv_examin_record_cancel, R.id.tv_examin_record_confirm,R.id.iv_add_train_record_pic})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                setResult(RESULT_OK, new Intent());
                finish();
                break;
            case R.id.ll_examin_name:
                initTrainRecordPop();
                break;
            case R.id.ll_examin_person:
                initTrainPersonPop();
                break;
            case R.id.ll_examin_date:
                initExaminTime();
                break;
            case R.id.ll_examin_degree:
                initDegreePop();
                break;
            case R.id.ll_examin_constractor:
                initContractorCompanyPop();
                break;
            case R.id.ll_examin_pass:
                initPassPop();
                break;
            case R.id.tv_examin_record_cancel:
                finish();
                break;
            case R.id.tv_examin_record_confirm:
                submit();
                break;
            case R.id.iv_add_train_record_pic:
                SelectPicUtils.takePic(AddExaminRecordActivity.this, SelectPicUtils.REQUEST_CODE_CHOOSE);
                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setSingle(false)  //设置是否单选
                        .start(AddExaminRecordActivity.this, Constants.REQUEST_CODE); // 打开相册
                break;
        }
    }

    private void initData() {
        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            mTv_common_title.setText("新增考试记录");
            mTv_examin_date.setText(DateTimeUtils.getCurrentYMD());
        } else {
            mTv_common_title.setText("修改考试记录");
            pageDataBean = (ExaminRecordListOutput.DataBean.PageDataBean) extras.getSerializable("RECORD_DATA");

            id = pageDataBean.getId();
            initExaminDetail();
            mTv_examin_name.setText(pageDataBean.getTrainingCoursewareName());
            mTv_examin_person.setText(pageDataBean.getPersonnelName());
            String examinationDate = pageDataBean.getExaminationDate();
            if (examinationDate.contains(" ")) {
                String[] split = examinationDate.split(" ");
                examinationDate = split[0];
            }
            mTv_examin_date.setText(examinationDate);
            mTv_examin_constractor.setText(pageDataBean.getContractorName());
            isPass = pageDataBean.isIsPass();
            if (isPass) {
                mTv_examin_pass.setText("合格");
            } else {
                mTv_examin_pass.setText("不合格");
            }
        }

        initBlackList();
    }

    /**
     * 考试详情
     */
    private void initExaminDetail() {
        Call<String> call = HttpManager.getInstance().requestService().EXAMIN_RECORD_DETAIL(id);
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                ExaminDetailOutput examinDetailOutput= new Gson().fromJson(result, ExaminDetailOutput.class);
                if (examinDetailOutput.getResult().equals("Success")) {
                    final ExaminDetailOutput.DataBean dataBean = examinDetailOutput.getData();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            degreeOfDifficulty = dataBean.getDegreeOfDifficulty();
                            if (degreeOfDifficulty.equals("1")) {
                                mTv_examin_degree.setText("困难");
                            } else {
                                mTv_examin_degree.setText("简单");
                            }
                            mEt_examin_score.setText(dataBean.getFraction() + "");
                            mEt_examin_mark.setText(dataBean.getRemarks());
                        }
                    });
                    cbsCourseId = dataBean.getCbsCourseId();
                    examinerId = dataBean.getExaminer();
                    cbsListId = dataBean.getCbsListId();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(examinDetailOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 培训课件名称-Pop
     */
    private void initTrainRecordPop() {
        View inflate = LayoutInflater.from(AddExaminRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(AddExaminRecordActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(AddExaminRecordActivity.this, R.layout.layout_item_common_more_department, MyApplication.getInstance().mListTrainCourse);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<TrainCourseOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, TrainCourseOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getTrainingCoursewareName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                TrainCourseOutput.DataBean.PageDataBean pageDataBean = MyApplication.getInstance().mListTrainCourse.get(position);
                cbsCourseId = pageDataBean.getId();
                String trainRecordName = pageDataBean.getTrainingCoursewareName();
                mTv_examin_name.setText(trainRecordName);
                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(AddExaminRecordActivity.this, inflate, mLl_examin_name);
    }

    /**
     * 培训人-Pop
     */
    private void initTrainPersonPop() {
        View inflate = LayoutInflater.from(AddExaminRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(AddExaminRecordActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(AddExaminRecordActivity.this, R.layout.layout_item_common_more_department, MyApplication.getInstance().mListParticipant);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<ContractorPersonOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, ContractorPersonOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getPersonnelName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                ContractorPersonOutput.DataBean.PageDataBean pageDataBean = MyApplication.getInstance().mListParticipant.get(position);
                examinerId = pageDataBean.getId();
                mTv_examin_person.setText(pageDataBean.getPersonnelName());

                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(AddExaminRecordActivity.this, inflate, mLl_examin_person);
    }

    /**
     * 考试日期
     */
    private void initExaminTime() {
        Calendar selectedDate = Calendar.getInstance();
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd");
                mTv_examin_date.setText(sdf_ymd.format(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setTitleSize(20)//标题文字大小
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.WHITE)//确定按钮文字颜色
                .setCancelColor(Color.WHITE)//取消按钮文字颜色
                .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
                .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();

        pvTime.show();
    }

    /**
     * 难易程度
     */
    private void initBlackList() {
        DropDownInput dropDownInput = new DropDownInput();
        List<String> categoryList = new ArrayList<>();
        categoryList.add("55");
        List<String> functionList = new ArrayList<>();
        dropDownInput.setCategoryCodeArray(categoryList);
        dropDownInput.setFunctionCodeArray(functionList);
        dropDownInput.setIsGetFactoryList(false);
        Call<String> call = HttpManager.getInstance().requestService().DROP_DOWN(HttpManager.getInstance().requestBody(dropDownInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                DropDownOutput dropDownOutput = new Gson().fromJson(result, DropDownOutput.class);
                if (dropDownOutput.getResult().equals("Success")) {
                    List<DropDownOutput.DataBean.DataDicListBean> dataDicList = dropDownOutput.getData().getDataDicList();
                    for (DropDownOutput.DataBean.DataDicListBean dataDicListBean : dataDicList) {
                        if (dataDicListBean.getKey().equals("55")) {
                            List<DropDownOutput.DataBean.DataDicListBean.ValueBean> valueBeanList = dataDicListBean.getValue();
                            mListDegree.addAll(valueBeanList);
                        }
                    }
                } else {
                    ToastUtils.getInstance().showShortToastBottom(dropDownOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });

    }


    /**
     * 难易程度-Pop
     */
    private void initDegreePop() {
        View inflate = LayoutInflater.from(AddExaminRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(AddExaminRecordActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(AddExaminRecordActivity.this, R.layout.layout_item_common_more_department, mListDegree);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<DropDownOutput.DataBean.DataDicListBean.ValueBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, DropDownOutput.DataBean.DataDicListBean.ValueBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getValue());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                DropDownOutput.DataBean.DataDicListBean.ValueBean valueBean = mListDegree.get(position);
                mTv_examin_degree.setText(valueBean.getValue());
                degreeOfDifficulty = valueBean.getKey();

                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(AddExaminRecordActivity.this, inflate, mLl_examin_degree);
    }

    /**
     * 承包商名称-Pop
     */
    private void initContractorCompanyPop() {
        View inflate = LayoutInflater.from(AddExaminRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(AddExaminRecordActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(AddExaminRecordActivity.this, R.layout.layout_item_common_more_department, MyApplication.getInstance().mListContractorCompany);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<ContractorCompanyOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, ContractorCompanyOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getContractorName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                ContractorCompanyOutput.DataBean.PageDataBean pageDataBean = MyApplication.getInstance().mListContractorCompany.get(position);
                cbsListId = pageDataBean.getId();
                mTv_examin_constractor.setText(pageDataBean.getContractorName());

                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(AddExaminRecordActivity.this, inflate, mLl_examin_constractor);
    }

    /**
     * 是否合格-Pop
     */
    private void initPassPop() {
        final List<String> mListPass = new ArrayList<>();
        mListPass.add("合格");
        mListPass.add("不合格");

        View inflate = LayoutInflater.from(AddExaminRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(AddExaminRecordActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(AddExaminRecordActivity.this, R.layout.layout_item_common_more_department, mListPass);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<String>() {
            @Override
            public void setItemData(CommonViewHolder holder, String dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean);
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                mTv_examin_pass.setText(mListPass.get(position));

                if (position == 0) {
                    isPass = true;
                } else {
                    isPass = false;
                }
                PopupWindowUtils.getInstance().closePop();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(AddExaminRecordActivity.this, inflate, mLl_examin_pass);
    }

    /**
     * 提交
     */
    private void submit() {
        String examinRecord = mTv_examin_name.getText().toString();
        if (TextUtils.isEmpty(examinRecord)) {
            ToastUtils.getInstance().showShortToastBottom("请选择培训记录!");
            return;
        }
        String examinPerson = mTv_examin_person.getText().toString();
        if (TextUtils.isEmpty(examinPerson)) {
            ToastUtils.getInstance().showShortToastBottom("请选择培训人!");
            return;
        }
        String examinDate = mTv_examin_date.getText().toString();
        String examinDegree = mTv_examin_degree.getText().toString();
        if (TextUtils.isEmpty(examinDegree)) {
            ToastUtils.getInstance().showShortToastBottom("请选择难易程度!");
            return;
        }
        String examinScore = mEt_examin_score.getText().toString();
        if (TextUtils.isEmpty(examinScore)) {
            ToastUtils.getInstance().showShortToastBottom("请输入考试分数!");
            return;
        }
        String constracotr = mTv_examin_constractor.getText().toString();
        if (TextUtils.isEmpty(constracotr)) {
            ToastUtils.getInstance().showShortToastBottom("请选择承包商名称!");
            return;
        }
        String eaxminPass = mTv_examin_pass.getText().toString();
        if (TextUtils.isEmpty(eaxminPass)) {
            ToastUtils.getInstance().showShortToastBottom("请选择是否合格!");
            return;
        }
        String marks = mEt_examin_mark.getText().toString();


        AddExaminRecordInput addExaminRecordInput = new AddExaminRecordInput();
        if (!TextUtils.isEmpty(id)) {
            addExaminRecordInput.setId(id);
        }
        addExaminRecordInput.setCbsCourseId(cbsCourseId);
        addExaminRecordInput.setExaminer(examinerId);
        addExaminRecordInput.setExaminationDate(examinDate);
        addExaminRecordInput.setDegreeOfDifficulty(degreeOfDifficulty);
        addExaminRecordInput.setFraction(Double.parseDouble(examinScore));
        addExaminRecordInput.setCbsListId(cbsListId);
        addExaminRecordInput.setIsPass(isPass);
        addExaminRecordInput.setCreateFactory("1");
        if (!TextUtils.isEmpty(marks)) {
            addExaminRecordInput.setRemarks(marks);
        }

        Call<String> call = HttpManager.getInstance().requestService().EXAMIN_RECORD_ADD(HttpManager.getInstance().requestBody(addExaminRecordInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                CommonOutput commonOutput = new Gson().fromJson(result, CommonOutput.class);
                if (commonOutput.getResult().equals("Success")) {
                    ToastUtils.getInstance().showShortToastBottom("提交成功!");
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putInt("SUCCESS", 1);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finishActivity(AddExaminRecordActivity.this);
                } else {
                    ToastUtils.getInstance().showShortToastBottom(commonOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    private void initPicRecyclerView() {
        GridLayoutManager glm = new GridLayoutManager(AddExaminRecordActivity.this, 4);
        mRv_pic.setLayoutManager(glm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRv_pic.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRv_pic.setItemAnimator(new DefaultItemAnimator());
        mRv_pic.setNestedScrollingEnabled(false);

        mCommonAdapter = new CommonAdapter(AddExaminRecordActivity.this, R.layout.layout_item_pic, mPicList);
        mCommonAdapter.setItemDatasListener(new CommonAdapter.ItemDatasListener<String>() {
            @Override
            public void setItemDatas(CommonViewHolder holder, String uri, int position) {
                ImageView iv_item = holder.getView(R.id.iv_item);
                Glide.with(AddExaminRecordActivity.this).load(uri).into(iv_item);
            }
        });

        mCommonAdapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {

            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {
                mPicList.remove(position);
                mPicIdList.remove(position);
                mCommonAdapter.notifyDataSetChanged();
            }
        });

        mRv_pic.setAdapter(mCommonAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        if (bundle == null)
            return;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.REQUEST_CODE:
                    ArrayList<String> images = data.getStringArrayListExtra(
                            ImageSelectorUtils.SELECT_RESULT);
                    mPicList.addAll(images);
                    if (mPicList.isEmpty()) {
                        mRv_pic.setVisibility(View.GONE);
                    } else {
                        mRv_pic.setVisibility(View.VISIBLE);
                        mCommonAdapter.notifyDataSetChanged();
                        uploadImages();
                    }
                    break;
            }
        }
    }

    /**
     * 上传照片
     */
    private void uploadImages() {
        if (mPicList.isEmpty())
            return;
        for (String path : mPicList) {
            File file = new File(path);
            if (!file.exists())
                break;
            final RequestBody requestFile =
                    RequestBody.create(MediaType.parse("application/otcet-stream"), file);
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("files", file.getName(), requestFile);

            Call<String> call = HttpManager.getInstance().requestService().UPLOAD_FILE(body);
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    UploadFileOutput uploadFileOutput = new Gson().fromJson(response.body(),UploadFileOutput.class);
                    if (uploadFileOutput.getResult().equals("Success")) {
                        String id = uploadFileOutput.getData().get(0).getId();
                        mPicIdList.add(id);
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    // Log.i("Simon", "uploadImages onFailure = " + t.getMessage());
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK, new Intent());
        super.onBackPressed();
    }
    
}
